/**
 * 
 */
package com.gmail.blackdog1987.carcare.activity;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gmail.blackdog1987.carcare.App;
import com.gmail.blackdog1987.carcare.BaseActivity;
import com.gmail.blackdog1987.carcare.Constant;
import com.gmail.blackdog1987.carcare.R;
import com.gmail.blackdog1987.carcare.db.dao.UserDao;
import com.gmail.blackdog1987.carcare.entity.TGasCard;
import com.gmail.blackdog1987.carcare.entity.TProduct;
import com.gmail.blackdog1987.carcare.util.GraphUtils;
import com.gmail.blackdog1987.carcare.util.HttpClientHelper;
import com.gmail.blackdog1987.carcare.util.MultipartEntityUtils;
import com.gmail.blackdog1987.carcare.util.ThreadPoolUtils;
import com.gmail.blackdog1987.carcare.widget.SelectPicPopupWindow;
import com.gmail.blackdog1987.carcare.widget.WheelPicker;
import com.google.gson.Gson;

public class GasCardActivity extends BaseActivity implements OnClickListener {
	private Context mContext;
	TGasCard card = new TGasCard();

	EditText name;
	EditText phone;
	EditText address;
	EditText idcard;
	TextView priceView;
	ImageView pic1;
	ImageView pic2;
	Bitmap bitmap1;
	Bitmap bitmap2;
	TextView sendtime;
	private MyHandler mHandler;
	private Uri mHeadUri1 = null;
	private Uri mHeadUri2 = null;

	private static final int REQUESTCODE_HEADPICKER = 100;
	private static final int REQUESTCODE_HEADPICKER2 = 200;
	private static final int RESPONSE_EDITOK = 1;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gas_applycard);
		mContext = this;
		if(new UserDao().getUser()==null){
			Toast.makeText(mContext, "请先登录", Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		initViews();
		initData(savedInstanceState);
		reg();
		mHandler = new MyHandler(this);
	}

	public void initViews() {
		name = (EditText) findViewById(R.id.gas_apply_name);
		phone = (EditText) findViewById(R.id.gas_apply_phone);
		address = (EditText) findViewById(R.id.gas_apply_address);
		idcard = (EditText) findViewById(R.id.gas_apply_idcard);
		pic1 = (ImageView) findViewById(R.id.gas_apply_idcard_pic);
		pic2 = (ImageView) findViewById(R.id.gas_apply_idcard_pic2);
		priceView = (TextView) findViewById(R.id.gas_apply_price);
		sendtime = (TextView) findViewById(R.id.gas_apply_time);
	}

	public void reg() {
		findViewById(R.id.gas_apply_ok).setOnClickListener(this);
		findViewById(R.id.back).setOnClickListener(this);
		priceView.setOnClickListener(this);
		pic1.setOnClickListener(this);
		pic2.setOnClickListener(this);
		sendtime.setOnClickListener(this);
	}

	public void initData(Bundle savedInstanceState) {
	}

	private boolean validInput() {
		if (name.getText().toString().trim().length() == 0 || phone.getText().toString().trim().length() == 0
				|| address.getText().toString().trim().length() == 0 || idcard.getText().toString().trim().length() == 0
				|| priceView.getText().toString().trim().length() == 0 || bitmap1 == null || bitmap2 == null) { // 
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.gas_apply_time:
			Intent timeIntent = new Intent(mContext, WheelPicker.class);
			timeIntent.putExtra("arrayid", R.array.gascard_sendtime);
			startActivityForResult(timeIntent, R.id.gas_apply_time);
			break;
		case R.id.gas_apply_price:
			Intent bodyIntent = new Intent(mContext, WheelPicker.class);
			String[] array = new String[App.CHARGE_VALUE_MAP.get("create").size()];
			for (int i = 0; i < array.length; i++) {
				array[i] = App.CHARGE_VALUE_MAP.get("create").get(i);
			}
			bodyIntent.putExtra("array", array);
			startActivityForResult(bodyIntent, R.id.gas_apply_price);
			break;
		case R.id.gas_apply_idcard_pic:
			Intent idIntent = new Intent(mContext, SelectPicPopupWindow.class);
			idIntent.putExtra(SelectPicPopupWindow.INTENT_EXTRA_KEY_TYPEMODE, SelectPicPopupWindow.TYPE_NORMAL);
			idIntent.putExtra("uri", "file:///sdcard/temp.jpg");
			startActivityForResult(idIntent, REQUESTCODE_HEADPICKER);
			break;
		case R.id.gas_apply_idcard_pic2:
			Intent idIntent2 = new Intent(mContext, SelectPicPopupWindow.class);
			idIntent2.putExtra(SelectPicPopupWindow.INTENT_EXTRA_KEY_TYPEMODE, SelectPicPopupWindow.TYPE_NORMAL);
			idIntent2.putExtra("uri", "file:///sdcard/temp2.jpg");
			startActivityForResult(idIntent2, REQUESTCODE_HEADPICKER2);
			break;
		case R.id.gas_apply_ok:
			if (validInput()) {
				loading();
				card = new TGasCard();
				card.name = name.getText().toString().trim();
				card.address = address.getText().toString().trim();
				card.phone = phone.getText().toString().trim();
				card.idcard = idcard.getText().toString().trim();
				card.price = Double.valueOf(priceView.getText().toString().trim());
				card.userid = new UserDao().getUser().id;
				card.sendtime = Integer.valueOf(sendtime.getText().toString().trim().length()==0?"0":sendtime.getText().toString().trim());
				ThreadPoolUtils.execute(new MyRunnable());
			}
		default:
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case REQUESTCODE_HEADPICKER:
				if (data != null) {
					Uri mImageCaptureUri = data.getData();
					if (mImageCaptureUri != null) {
						Bitmap image;
						try {
							image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri);
							if (image != null) {
								pic1.setImageBitmap(image);
								bitmap1 = image;
							} else {
								bitmap1 = null;
							}
						} catch (Exception e) {
							bitmap1 = null;
							e.printStackTrace();
						}
					} else {
						Bundle extras = data.getExtras();
						if (extras != null) {
							Bitmap image = extras.getParcelable("data");
							if (image != null) {
								pic1.setImageBitmap(image);
								bitmap1 = image;
							} else {
								bitmap1 = null;
							}
						}
					}
					mHeadUri1 = mImageCaptureUri;
				}
				break;
			case REQUESTCODE_HEADPICKER2:
				if (data != null) {
					Uri mImageCaptureUri = data.getData();
					if (mImageCaptureUri != null) {
						Bitmap image;
						try {
							image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri);
							if (image != null) {
								pic2.setImageBitmap(image);
								bitmap2 = image;
							} else {
								bitmap2 = null;
							}
						} catch (Exception e) {
							bitmap2 = null;
							e.printStackTrace();
						}
						mHeadUri2 = mImageCaptureUri;
					} else {
						Bundle extras = data.getExtras();
						if (extras != null) {
							Bitmap image = extras.getParcelable("data");
							if (image != null) {
								pic2.setImageBitmap(image);
								bitmap2 = image;
							} else {
								bitmap2 = null;
							}
						}
					}
				}
				break;
			case R.id.gas_apply_price:
				priceView.setText(data.getStringExtra("resultdata"));
				break;
			case R.id.gas_apply_time:
				sendtime.setText(data.getStringExtra("resultdata"));
				break;
			case PayActivity.REQUESTCODE_PAY:
				Toast.makeText(mContext, "恭喜您支付成功", Toast.LENGTH_LONG).show();
				finish();
				break;
			}
		}
	}

	private static class MyHandler extends Handler {
		private WeakReference<GasCardActivity> mOuter;

		public MyHandler(GasCardActivity activity) {
			mOuter = new WeakReference<GasCardActivity>(activity);
		}

		@Override
		public void dispatchMessage(Message msg) {
			GasCardActivity outer = mOuter.get();
			switch (msg.what) {
			case RESPONSE_EDITOK:
				outer.loadingFinish();
				if (msg.obj == null) {
					// 执行失败
				}
				JSONObject json = null;
				try {
					json = new JSONObject((String) msg.obj);
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					if (!(Boolean) json.get("success")) {
						Toast.makeText(outer.mContext, "保存失败", Toast.LENGTH_SHORT).show();
						return;
					}
					TGasCard card = new Gson().fromJson(json.getJSONObject("record").toString(), TGasCard.class);
					if(card==null){
						Toast.makeText(outer.mContext, "申请失败", Toast.LENGTH_SHORT).show();
						return;
					}
//					Toast.makeText(outer.mContext, "申请成功！", Toast.LENGTH_SHORT).show();
//					outer.finish();
					TProduct product = new TProduct();
					product.body = "加油卡";
					product.price = Double.valueOf(outer.priceView.getText().toString());
					product.subject = "车拉丁";
					product.tableName = "t_gas_card";
					product.tableId = card.getId();
					product.userid = new UserDao().getUser().id;
					Intent i = new Intent(outer, PayActivity.class);
					i.putExtra("data", product);
					outer.startActivityForResult(i, PayActivity.REQUESTCODE_PAY);
				} catch (JSONException e) {
					Toast.makeText(outer.mContext, "保存失败", Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
				break;
			default:
				Toast.makeText(outer.mContext, "未知错误", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	}

	private class MyRunnable implements Runnable {
		@Override
		public void run() {
			HttpClient httpclient = HttpClientHelper.getHttpClient();
			// 请求处理页面
			HttpPost httppost = new HttpPost(Constant.Action.GAS_APPLYCARD);

			try {
				// 对请求的表单域进行填充
				MultipartEntity reqEntity = new MultipartEntity();
				MultipartEntityUtils.initGasCard(reqEntity, card);

				FileBody file1 = null;
				
				if(mHeadUri1==null){
					if (bitmap1 != null) {
						file1 = new FileBody(GraphUtils.Bitmap2File(App.getInstance(), bitmap1, "pic"));
					}
				}else{
					try {
						file1 = new FileBody(new File(new URI(mHeadUri1.toString())));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (file1 != null) {
					reqEntity.addPart("pic", file1);
				}

				FileBody file2 = null;
				
				if(mHeadUri2==null){
					if (bitmap2 != null) {
						file2 = new FileBody(GraphUtils.Bitmap2File(App.getInstance(), bitmap2, "pic2"));
					}
				}else{
					try {
						file2 = new FileBody(new File(new URI(mHeadUri2.toString())));
					} catch (URISyntaxException e) {
						e.printStackTrace();
					}
				}
				
				if (file2 != null) {
					reqEntity.addPart("pic2", file2);
				}

				// 设置请求
				httppost.setEntity(reqEntity);

				// 执行
				HttpResponse response = httpclient.execute(httppost);
				/** 请求发送成功，并得到响应 **/
				if (response.getStatusLine().getStatusCode() == 200) {
					byte[] bytes = EntityUtils.toByteArray(response.getEntity());
					// 在大多数情况下，这个下载下来的是XML或者Json。应该解析完组装成对象再放置到Message中。
					// 这里简单起见，直接变成字符串打印了
					String result = new String(bytes);

					Message msg = mHandler.obtainMessage();
					msg.what = RESPONSE_EDITOK;
					msg.obj = result;

					mHandler.sendMessage(msg);
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public void loading() {
		if (findViewById(R.id.gas_apply_ok) != null && findViewById(R.id.loading) != null) {
			findViewById(R.id.gas_apply_ok).setVisibility(View.GONE);
			findViewById(R.id.loading).setVisibility(View.VISIBLE);
		}

	}

	public void loadingFinish() {
		if (findViewById(R.id.gas_apply_ok) != null && findViewById(R.id.loading) != null) {
			findViewById(R.id.gas_apply_ok).setVisibility(View.VISIBLE);
			findViewById(R.id.loading).setVisibility(View.GONE);
		}
	}
}
